/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.scene.domain.JSATemplate;
import com.koron.scene.domain.JSATemplateStep;
import com.koron.scene.mapper.JSATemplateMapper;
import com.koron.scene.mapper.JSATemplateStepMapper;
import com.koron.scene.service.api.JSATemplateService;
import com.koron.scene.utils.BusinessCode;
import com.koron.system.domain.DictData;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class JSATemplateServiceImpl implements JSATemplateService {

    private final static  Logger logger = LoggerFactory.getLogger(JSATemplateServiceImpl.class);

    @Autowired
    private DictDataService dataService;

    @Override
    public DataBean<JSATemplate> fetchTemplates(String name, String jsaTypeId, Integer start, Integer rows) {
        if (logger.isDebugEnabled()) {
            logger.debug("name = {}, jsaTypeId = {}", name, jsaTypeId);
        }
        try (SessionFactory factory = new SessionFactory()) {
            JSATemplateMapper mapper = factory.getMapper(JSATemplateMapper.class);
            List<JSATemplate> jsaTemplates = mapper.queryByCondition(name, jsaTypeId, start, rows);
            Integer total = mapper.countByCondition(name, jsaTypeId);
            if (!jsaTemplates.isEmpty()) {
                jsaTemplates.forEach(template -> {
                    setName(template);
                    template.setSteps(factory.getMapper(JSATemplateStepMapper.class).querySteps(template.getId()));
                });
            }
            DataBean<JSATemplate> dataBean = new DataBean<>();
            dataBean.setList(jsaTemplates);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(total);
            if (rows != null) {
                dataBean.setTotalPage(total > rows ? (total % rows == 0 ? total / rows : total / rows + 1) : 1);
                dataBean.setPageNo(start / rows + 1);
            }
            return dataBean;
        }
    }


    @Override
    public JSATemplate fetchOne(String id) {
        if (logger.isDebugEnabled()) {
            logger.debug("id = {}", id);
        }
        try (SessionFactory factory = new SessionFactory()) {
            JSATemplate template = factory.getMapper(JSATemplateMapper.class).queryOne(id);
            if (template != null) {
                setName(template);
                template.setSteps(factory.getMapper(JSATemplateStepMapper.class).querySteps(id));
            }
            return template;
        }
    }

    private void setName(JSATemplate template) {
        Map<String, DictData> cacheMap = dataService.getCacheMap();
        if (StringUtils.isNotBlank(template.getJsaTypeId())) {
            DictData dictData = cacheMap.get(template.getJsaTypeId());
            template.setJsaTypeName(dictData != null? dictData.getDictLabel() : "");
        }
    }

    @Override
    public Boolean batchDetele(List<String> idList) {
        SessionFactory factory = null;
        if (idList == null || idList.isEmpty()) {
            return true;
        }
        try {
            factory = new SessionFactory();
            for (String id : idList) {
                factory.getMapper(JSATemplateStepMapper.class).deleteSteps(id);
            }
            factory.getMapper(JSATemplateMapper.class).batchDetele(idList);
            factory.close(true);
            return true;
        } catch (Exception e) {
            if (factory != null) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
        }
        return false;
    }



    @Override
    public Integer persist(JSATemplate template) {
        SessionFactory factory = null;
        try {
            Integer start = null, rows = null;
            String jsaTypeId = null;
            JSATemplate dest = null;
            factory = new SessionFactory();
            JSATemplateMapper mapper = factory.getMapper(JSATemplateMapper.class);
            List<JSATemplate> jsaTemplates = mapper.queryByCondition(template.getName(), jsaTypeId, start, rows);
            if (jsaTemplates != null && !jsaTemplates.isEmpty()) {
                jsaTemplates = jsaTemplates.stream().filter(one -> one.getName().equals(template.getName())).collect(Collectors.toList());
                dest = !jsaTemplates.isEmpty() ? jsaTemplates.get(0) : null;
            }

            if (StringUtils.isBlank(template.getId())) {
                if (dest != null) {
                    factory.close(false);
                    return BusinessCode.JSATEMPLATE_NAME_DUP.getCode();
                }
                template.setId(DefaultIdGenerator.getInstance().generateLongId());
                if (mapper.insert(template) > 0 && persistSteps(factory, template.getSteps(), template.getId())) {
                    factory.close(true);
                    return BusinessCode.SUCCESS.getCode();
                }
            } else {
                if (dest != null && !dest.getId().equals(template.getId())) {
                    factory.close(false);
                    return BusinessCode.JSATEMPLATE_NAME_DUP.getCode();
                }
                if (mapper.update(template) > 0 && persistSteps(factory, template.getSteps(), template.getId())) {
                    factory.close(true);
                    return BusinessCode.SUCCESS.getCode();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        if (factory != null) {
            factory.close(false);
        }
        return BusinessCode.EXCEPTION.getCode();
    }


    private boolean persistSteps(SessionFactory factory, List<JSATemplateStep> steps, String templateId) {
        try {
            if (steps == null || steps.isEmpty()) {
                return true;
            }
            steps.stream().forEach(s -> s.setTemplateId(templateId));
            JSATemplateStepMapper mapper = factory.getMapper(JSATemplateStepMapper.class);
            List<JSATemplateStep> ulist = steps.stream().filter(templateStep -> StringUtils.isNotBlank(templateStep.getId())).collect(Collectors.toList());
            List<JSATemplateStep> ilist = steps.stream().filter(templateStep -> StringUtils.isBlank(templateStep.getId())).collect(Collectors.toList());
            List<JSATemplateStep> formers = mapper.querySteps(templateId);
            formers.removeAll(ulist);
            if (!ulist.isEmpty()) {
                mapper.batchUpdate(ulist);
            }
            if (!ilist.isEmpty()) {
                for (JSATemplateStep jsaTemplateStep : ilist) {
                    jsaTemplateStep.setId(DefaultIdGenerator.getInstance().generateLongId());
                }
                mapper.batchInsert(ilist);
            }
            if (!formers.isEmpty()) {
                mapper.batchDetele(formers.stream().map(JSATemplateStep::getId).collect(Collectors.toList()));
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return false;
        }
    }


}
